//
//  UserDataViewController.swift
//  GhostWorld
//
//  Created by Jingmei Tan on 2019/12/26.
//  Copyright © 2019 LKGood. All rights reserved.
//

import UIKit
import AlamofireImage
import Alamofire
import SwiftyJSON
import PKHUD

class UserDataViewController: BaseViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {

    
    @IBOutlet weak var headImgButton: UIButton!
    @IBOutlet weak var nickNameButton: UIButton!
    @IBOutlet weak var sexInfoButton: UIButton!
    @IBOutlet weak var phoneNumButton: UIButton!
    @IBOutlet weak var emailInfoButton: UIButton!
    @IBOutlet weak var changePasswordButton: UIButton!
    
    private var avatarImage: UIImage?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.headImgButton.layer.cornerRadius = self.headImgButton.width / 2
        self.headImgButton.layer.masksToBounds = true
        self.showUserInfo()
        // Do any additional setup after loading the view.
    }
    
    // MARK:- request
    
    func uploadHeadImg(_ image:UIImage) {
        HUD.show(.labeledProgress(title: "请稍后", subtitle: nil))
        let headers: HTTPHeaders = [
            "Accept": "application/json;charset=utf-8",
            "lang":"en-US",
            "content-type":"multipart/form-data",
        ]
        Alamofire.upload(multipartFormData: { (formData) in
            if let imageData = image.pngData() {
                formData.append(imageData, withName: "file",fileName: "image.png",mimeType: "image/png")
            }
            formData.append("\(UserManager.shared.currentUser!.identifier)".data(using: .utf8)!, withName: "uid")
            formData.append("change_img".data(using: .utf8)!, withName: "type")
            
        }, usingThreshold: 50*1024*1024, to: URL.init(string: APIURLStrings.userInfoCheck)!, method: .post, headers: headers) { (encodingResult) in
            switch (encodingResult) {
            case .success(let upload, _, _):
                upload.responseJSON { (response) in
                    switch response.result {
                    case .success(let value):
                        let json = JSON(value)
                        let success = json["status"].boolValue
                        if success {
                            HUD.flash(.labeledSuccess(title: "头像更换成功", subtitle: nil), delay: 1.5)
                            self.headImgButton.setBackgroundImage(image, for: .normal)
                            if let imagePath = json["data"]["img"].string {
                                UserManager.shared.currentUser!.avatar.thumbPath = imagePath
                                UserManager.shared.updateUserDefault()
                                NotificationCenter.default.post(name: .updateUserInfo, object: [UserDataChangeType.HeadImage:image])
                            }
                        }
                        else {
                            HUD.flash(.labeledError(title: "头像更换失败", subtitle: "请稍后重试"), delay: 1.5)
                        }
                    case .failure(_):
                        HUD.flash(.labeledError(title: "头像更换失败", subtitle: "请稍后重试"), delay: 1.5)
                    }
                }
            case .failure(_):
                HUD.flash(.labeledError(title: "头像更换失败", subtitle: "请稍后重试"), delay: 1.5)
            }
        }
    }
        
    // MARK:- PrepareUI
    
    private func showUserInfo() {
        let user = UserManager.shared.currentUser!
        if let imageURL = user.avatar.getURL(size: .thumb) {
            self.headImgButton.af_setBackgroundImage(for: .normal, url: imageURL)
        }
        
        let nickName = "昵称：" + user.nickname!
        self.nickNameButton.setTitle(nickName, for: .normal)
        
        var gendarStr = "保密"
        switch (user.gender) {
        case .male:gendarStr = "男"; break
        case .female:gendarStr = "女"; break
        default:gendarStr = "保密"; break
        }
        let sex = "性别：" + gendarStr;
        self.sexInfoButton.setTitle(sex, for: .normal)
        
        let phoneNumer = "电话：" + user.cellPhone!
        self.phoneNumButton.setTitle(phoneNumer, for: .normal)
        
        let email = "邮箱：" + user.email!
        self.emailInfoButton.setTitle(email, for: .normal)
        
        NotificationCenter.default.addObserver(self, selector: #selector(userInfoUpdated(_:)), name: .updateUserInfo, object: nil)
        
    }
    
    @IBAction func actionHeadImgButton(_ sender: UIButton) {
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            //show a actrionSheet to choose photo library or camera
            let alert = UIAlertController(title: "头像来源", message: nil, preferredStyle: .actionSheet)
            alert.view.tintColor = UIColor(fromPreeset: .globalTint)
            let cameraAction = UIAlertAction(title: "相机", style: .default, handler: { _ in
                self.showImagePicker(sourceType: .camera)
            })
            let cameraRollAction = UIAlertAction(title: "照片库", style: .default, handler: { _ in
                self.showImagePicker(sourceType: .photoLibrary)
            })
            let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            
            alert.addAction(cameraAction)
            alert.addAction(cameraRollAction)
            alert.addAction(cancelAction)
            
            present(alert, animated: true)
        } else {
            showImagePicker(sourceType: .photoLibrary)
        }
    }
    
    private func showImagePicker(sourceType: UIImagePickerController.SourceType) {
        
        let picker = UIImagePickerController()
        picker.view.tintColor = UIColor(fromPreeset: .globalTint)
        picker.delegate = self
        picker.allowsEditing = true
        picker.sourceType = sourceType
        
        picker.navigationBar.tintColor = UIColor(fromPreeset: .globalTint)
        picker.navigationBar.barTintColor = UIColor(fromPreeset: .navBarTint)
        picker.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor(fromPreeset: .navTitleColor)]
        picker.navigationBar.isTranslucent = false
        
        present(picker, animated: true)
    }
    
    @IBAction func actionBeginToChange(_ sender: UIButton) {
        if sender == self.nickNameButton {
            self.performSegue(withIdentifier: "PushToUserDataChange", sender: "nick_name")
        }
        else if sender == self.sexInfoButton {
            self.performSegue(withIdentifier: "PushToUserDataChange", sender: "sex")
        }
        else if sender == self.phoneNumButton {
            self.performSegue(withIdentifier: "PushToUserDataChange", sender: "phone")
        }
        else if sender == self.emailInfoButton {
            self.performSegue(withIdentifier: "PushToUserDataChange", sender: "email")
        }
        else if sender == self.changePasswordButton {
            self.performSegue(withIdentifier: "PushToUserDataChange", sender: "password")
        }
    }
    
    
    // MARK: - Navigation
    
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let controller = segue.destination as! UserDataChangeViewController
        if sender as! String == "nick_name" {
            controller.navigationItem.title = "修改昵称"
            controller.type = .NickName
        }
        else if sender as! String == "sex" {
            controller.navigationItem.title = "修改性别"
            controller.type = .Sex
        }
        else if sender as! String == "phone" {
            controller.navigationItem.title = "修改手机"
            controller.type = .Phone
        }
        else if sender as! String == "email" {
            controller.navigationItem.title = "修改邮箱"
            controller.type = .Email
        }
        else if sender as! String == "password" {
            controller.navigationItem.title = "修改密码"
            controller.type = .Password
        }
    }
    
    // MARK:- PickerDelegate
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        // Local variable inserted by Swift 4.2 migrator.
        let info = convertFromUIImagePickerControllerInfoKeyDictionary(info)
        
        var image = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.editedImage)] as? UIImage
        if image == nil {
            image = info[convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.originalImage)] as? UIImage
        }
        if image != nil {
            UIGraphicsBeginImageContext(CGSize(width: 100.0, height: 100.0))
            image!.draw(in: CGRect(x: 0, y: 0, width: 100.0, height: 100.0))
            avatarImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            
            if let image = avatarImage {
                dismiss(animated: true, completion: {
                    DispatchQueue.main.async {
                        self.uploadHeadImg(image)
                    }
                })
            }
        }
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        dismiss(animated: true) {
            
        }
    }
    
    @objc func userInfoUpdated(_ sender:Notification) {
        let info = sender.object as! Dictionary<UserDataChangeType, Any>
        let value = info.values.first!
        switch info.keys.first {
        case .NickName:
            self.nickNameButton.setTitle("昵称：\(value)", for: .normal)
        case .Sex:
            let sexInfo = value as! Int
            self.sexInfoButton.setTitle("性别："+(sexInfo == 11 ? "保密" : sexInfo == 1 ? "男" : "女"), for: .normal)
        case .Phone:
            self.phoneNumButton.setTitle("电话：\(value)", for: .normal)
        case .Email:
            self.emailInfoButton.setTitle("邮箱：\(value)", for: .normal)
        default: break
            
        }
    }
}

// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromUIImagePickerControllerInfoKeyDictionary(_ input: [UIImagePickerController.InfoKey: Any]) -> [String: Any] {
    return Dictionary(uniqueKeysWithValues: input.map {key, value in (key.rawValue, value)})
}

// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromUIImagePickerControllerInfoKey(_ input: UIImagePickerController.InfoKey) -> String {
    return input.rawValue
}
